import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import ECharts from '@kuiper-components/echarts';
import ChartTitle from '../../../../../../../components/ChartTitle';
import s from './style.module.css';
import moment from 'moment';

const lineOptionEmpty = (st, et) => {
	return {
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross',
			},
			formatter: value => {
				let html = `<div><p>${moment(value[0].value[0]).format(
					'YYYY-MM-DD HH:mm:ss'
				)}</p>`;
				value.map(item => {
					html += `<div>`;
					html += `<div style="width: 8px;height: 8px;border-radius: 50%;background-color: ${item.color};margin-right: 5px;display: inline-block;vertical-align:middle;"></div>`;
					html += `<div style="display:inline-block;vertical-align:middle;">${item.seriesName} ${item.value[1]}ms</div>`;
					html += `</div>`;
				});
				html += `</div>`;
				return html;
			},
			backgroundColor: '#fff',
			textStyle: '#696C78',
			extraCssText:
				'width: max-content;max-width: 20rem;white-space: pre-wrap;padding:1rem;line-height:1rem;margin: 0 auto;box-shadow: 0 4px 4px -1px rgba(0, 0, 0, 0.2);',
		},
		legend: {
			data: ['暂无数据'],
		},
		series: [
			{
				name: '暂无数据',
				data: [
					[st, 0],
					[et, 0],
				],
				type: 'line',
				smooth: false,
				showSymbol: false,
			},
		],
		xAxis: {
			type: 'time',
			boundaryGap: false,
			splitLine: { show: false },
			// maxInterval: 3600 * 24 * 1000,
			axisLine: { show: false },
			axisLabel: {
				formatter: function (value) {
					return moment(value)
						.format('MM-DD HH')
						.split(' ')
						.reverse()
						.join('\n');
				},
				showMinLabel: true,
				showMaxLabel: true,
			},
			// interval: 1000 * 60 * 60 * 24,
			axisTick: { lineStyle: { opacity: 0 } },
		},
		yAxis: {
			type: 'value',
			axisLabel: {
				show: true,
				interval: 'auto',
				formatter: '{value} ms',
			},
			axisLine: { show: false },
			axisTick: { lineStyle: { opacity: 0 } },
			splitLine: { lineStyle: { color: '#F7F9FC' } },
		},
		textStyle: { color: '#696C78', fontSize: 12 },
	};
};

function ResponseTime({ className, resultNumbers, keyStr }) {
	let st = new Date(new Date().getTime() - 3600 * 24 * 1000).toISOString();
	let et = new Date().toISOString();
	if (resultNumbers.length && resultNumbers[0].id === 'empty') {
		st = resultNumbers[0].datetime;
		et = resultNumbers[1].datetime;
	}
	const lineOption = Object.assign({}, lineOptionEmpty(st, et));

	const [linesOption, setLinesdata] = React.useState(lineOption);
	React.useMemo(() => {
		let lineData = {};
		for (let i = 0; i < resultNumbers.length; i++) {
			const datetime = resultNumbers[i].datetime;
			const detail = resultNumbers[i]?.aviliable;
			for (let j = 0; j < detail.length; j++) {
				const name =
					detail[j].area +
					(detail[j].networkDisplayName
						? ' ' + detail[j].networkDisplayName
						: '');
				if (name && !lineData[name]) {
					lineData[name] = [[datetime, detail[j].totalTime]];
				} else if (lineData[name]) {
					lineData[name].push([datetime, detail[j].totalTime]);
				}
			}
		}
		lineData = Object.keys(lineData).reduce((t, key) => {
			t[key] = lineData[key].sort((a, b) => {
				return moment(a[0]).unix() - moment(b[0]).unix();
			});
			return t;
		}, {});
		const legend = [];
		let line = [];
		line = Object.entries(lineData).map(([name, data]) => {
			legend.push(name);
			const res = {
				name,
				data,
				type: 'line',
				smooth: false,
				showSymbol: false,
			};
			return res;
		});

		if (line.length === 0) {
			line = [
				{
					name: '暂无数据',
					data: [
						[st, 0],
						[et, 0],
					],
					type: 'line',
					smooth: false,
					showSymbol: false,
				},
			];
		}
		lineOption.series = line;
		lineOption.legend.data = legend;
		const linesdata = Object.assign({}, lineOption);
		setLinesdata(linesdata);
	}, [resultNumbers, keyStr]);
	return (
		<div className={cn(className, s.responseTime)}>
			<div className={s.head}>
				<ChartTitle className={s.title}>平均响应时间</ChartTitle>
			</div>
			{resultNumbers.length && resultNumbers[0]?.id === 'empty' ? (
				<ECharts className={s.chart} option={linesOption} key={keyStr} />
			) : (
				<ECharts className={s.chart} option={linesOption} key={keyStr + '1'} />
			)}
		</div>
	);
}

ResponseTime.propTypes = {
	className: PropTypes.string,
	keyStr: PropTypes.string,
	resultNumbers: PropTypes.arrayOf(
		PropTypes.shape({
			datetime: PropTypes.date,
			aviliable: PropTypes.arrayOf(
				PropTypes.shape({
					area: PropTypes.string,
					respTime: PropTypes.number,
				})
			),
		})
	),
};
ResponseTime.defaultProps = {
	className: '',
};

export default ResponseTime;
